//
//  PhoneLoginController.m
//  EncryPhone
//
//  Created by zhibao on 2022/9/26.
//

#import "LoginController.h"
#import "LoginCodeInputController.h"
@interface LoginController (){
    QMUITextField *phoneField;
    UIButton *selectBtn;
    NSString *selectCode;
    UIButton *nextBtn;
}

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    selectCode = @"86";
    [self initNavView];
    [self initView];
    self.view.backgroundColor = UIColor.whiteColor;
}
-(void)initNavView{
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(0, 0, 60, 40);
    [cancelBtn setImage:[UIImage imageNamed:@"arrow_back"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(navBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithCustomView:cancelBtn];
    self.gk_navLeftBarButtonItems = @[item2];
    //self.gk_backImage = [UIImage imageNamed:@"arrow_back_white"]
}

-(void)navBtnClick{
    DLog(@"使用导航");
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)initView{
    UILabel *clabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 103 - 64 + NAVIH, MY_Screen_W - 60, 80)];
    clabel.text = LocalizedString(@"欢迎登录二维码制作助手");
    clabel.font = MY_SCALE_RegularFONT(25);
    clabel.numberOfLines = 0;
    clabel.lineBreakMode = NSLineBreakByWordWrapping;
    clabel.textColor = MYBlock;
    [self.view addSubview:clabel];
    
    
    selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
 //    selectBtn.frame = CGRectMake(clabel.left, clabel.bottom + 61, 80, 36);
    [selectBtn setTitle:@"+86 ▼" forState:UIControlStateNormal];
    [selectBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [selectBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    selectBtn.titleLabel.font = MY_SCALE_RegularFONT(14);
    [self.view addSubview:selectBtn];
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(clabel);
        make.top.equalTo(clabel.mas_bottom).offset(61);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(36);
    }];
    
    phoneField = [[QMUITextField alloc]init];
    phoneField.placeholder = LocalizedString(@"请输入手机号");
    phoneField.placeholderColor = MyColor(@"777777");
    phoneField.textColor = MYBlock;
    phoneField.font = MY_SCALE_RegularFONT(13);
    [phoneField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:phoneField];
    [phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn.mas_right).offset(10);
        make.right.mas_equalTo(-30);
        make.centerY.height.equalTo(selectBtn);
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = MyColor(@"#d8d8d8");
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn);
        make.right.equalTo(phoneField);
        make.top.equalTo(phoneField.mas_bottom);
        make.height.mas_equalTo(0.5);
    }];
    
    UILabel *cplabel = [[UILabel alloc]init];
    cplabel.text = LocalizedString(@"未注册的手机号验证后将自动创建账户");
    cplabel.numberOfLines = 0;
    cplabel.lineBreakMode = NSLineBreakByWordWrapping;
    cplabel.font = MY_SCALE_RegularFONT(12);
    cplabel.textColor = MyColor(@"666666");
    [self.view addSubview:cplabel];
    [cplabel  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn);
        make.right.equalTo(phoneField);
        make.top.equalTo(line.mas_bottom).offset(8);
    }];
    
    
    nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.layer.cornerRadius = 20;
    nextBtn.backgroundColor = MyColor(@"#D7E8FF");
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectBtn);
        make.right.equalTo(phoneField);
        make.top.equalTo(cplabel.mas_bottom).offset(60);
        make.height.mas_equalTo(40);
    }];
    [nextBtn setTitle:LocalizedString(@"获取验证码") forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.titleLabel.font = MY_SCALE_SemiboldFONT(13);
    [nextBtn setTitleColor:MyColor(@"ffffff") forState:UIControlStateNormal];
    
    if ([Helper validateWithStartTime:@"2022-11-09 17:00:00" withExpireTime:@"2023-06-03 10:00:00"]) {
        UIButton *youkeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        youkeBtn.frame = CGRectMake(30, nextBtn.bottom + 30, MY_Screen_W - 60, 40);
        youkeBtn.layer.cornerRadius = 20;
        youkeBtn.backgroundColor = MYBlue;
        [self.view addSubview:youkeBtn];
        [youkeBtn setTitle:LocalizedString(@"游客登录") forState:UIControlStateNormal];
        [youkeBtn addTarget:self action:@selector(youkeLogin) forControlEvents:UIControlEventTouchUpInside];
        youkeBtn.titleLabel.font = MY_SCALE_SemiboldFONT(15);
        [youkeBtn setTitleColor:MyColor(@"ffffff") forState:UIControlStateNormal];
        [youkeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(selectBtn);
            make.right.equalTo(phoneField);
            make.top.equalTo(nextBtn.mas_bottom).offset(30);
            make.height.mas_equalTo(40);
        }];
    }
    
//    nextBtn.userInteractionEnabled = NO;
    
    YYLabel *bottomLabel = [[YYLabel alloc]init];
    bottomLabel.lineBreakMode = NSLineBreakByWordWrapping;
    bottomLabel.numberOfLines = 0;
    bottomLabel.textAlignment = NSTextAlignmentCenter;
    //bottomLabel.centerX = MY_Screen_W / 2;
    
    bottomLabel.preferredMaxLayoutWidth = MY_Screen_W - 60;
    [self.view addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.bottom.mas_equalTo(- 23 - 20);
        make.right.mas_equalTo(-30);
    }];
    
    NSMutableString *string = [[NSMutableString alloc]initWithString:LocalizedString(@"登录即代表同意")];
    [string appendString:@"《"];
    [string appendString:LocalizedString(@"用户协议")];
    [string appendString:@"》"];
    [string appendString:LocalizedString(@"和")];
    [string appendString:@"《"];
    [string appendString:LocalizedString(@"隐私协议")];
    [string appendString:@"》"];
    NSRange yhrange = [string rangeOfString:LocalizedString(@"用户协议")];
    NSRange xyrange = [string rangeOfString:LocalizedString(@"隐私协议")];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string];
    attri.yy_font = MY_SCALE_RegularFONT(11);
    attri.yy_color = MYBlock;
    __weak typeof(self) weakSelf = self;
    [attri yy_setTextHighlightRange:NSMakeRange(yhrange.location - 1, yhrange.length + 2) color:MYBlue backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        WebViewController *controller = [[WebViewController alloc] initWithtitle:LocalizedString(@"用户协议") WithUrl:@"https://docs.qq.com/doc/DRlRsT2NLUnFieVZr"];
        [strongSelf.navigationController pushViewController:controller animated:YES];
    }];
    
    [attri yy_setTextHighlightRange:NSMakeRange(xyrange.location - 1, xyrange.length + 2) color:MYBlue backgroundColor:UIColor.clearColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        WebViewController *controller = [[WebViewController alloc] initWithtitle:LocalizedString(@"隐私协议") WithUrl:@"https://docs.qq.com/doc/DRndzeXVxVXN6VFRJ"];
        [strongSelf.navigationController pushViewController:controller animated:YES];
    }];
    bottomLabel.attributedText = attri;
    bottomLabel.textAlignment = NSTextAlignmentCenter;
}
-(void)youkeLogin{
    [[HttpHelper sharedInstance] sendPost:@"api/user/tourists/login" parameters:@{@"uuid":[Helper getOnlyStr]} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        if (responseObject.code == 1) {
            [UserInfoManager sharedManager].iToken = responseObject.data[@"data"][@"token"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UserInfoManager sharedManager] analyzeUserIToken:responseObject.data[@"data"][@"token"]];
                TabBarController *tabbarController = [[TabBarController alloc] init];
                MYAPP.tarbar = tabbarController;
                MYAPP.window.rootViewController = tabbarController;
            });
        }
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}

-(void)nextClick{
    if(phoneField.text.qmui_trim.length < 1){
        [QMUITips showError:LocalizedString(@"请输入号码！")];
        return;
    }
    NSDictionary *dic =@{
        @"phone":phoneField.text,
        @"areaCode":selectCode
    };
    [QMUITips showLoadingInView:self.view];
    [[HttpHelper sharedInstance] sendPost:@"api/sms/login/send" parameters:dic success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        DLog(@"code===%@",responseObject.data);
        [QMUITips hideAllTipsInView:self.view];
        if (responseObject.code == 1) {
            LoginCodeInputController *controller = [LoginCodeInputController new];
            controller.type = 4;
            controller.areaCode = self->selectCode;
            controller.phone = self->phoneField.text.qmui_trimAllWhiteSpace;
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            [QMUITips showError:responseObject.message];
        }
        
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        [QMUITips hideAllTipsInView:self.view];
    }];
}

-(void)btnClick:(UIButton *)sender{
    NSMutableArray *codeArray = [NSMutableArray new];
    [[HttpHelper sharedInstance] sendGet:@"api/area/code" parameters:@{} success:^(NSURLSessionTask * _Nonnull operation, ResponseModel * _Nonnull responseObject) {
        DLog(@"code===%@",responseObject.data);
        for (int i = 0; i < [responseObject.data[@"data"] count]; i++) {
            NSDictionary *dic = responseObject.data[@"data"][i];
            [codeArray addObject:dic[@"code"]];
        }
        CGXPickerViewManager *manager = [CGXPickerViewManager new];
//        manager.rightBtnTitleColor = UIColor.whiteColor;
        [CGXPickerView showStringPickerWithTitle:@"" DataSource:codeArray DefaultSelValue:nil IsAutoSelect:NO Manager:manager ResultBlock:^(id selectValue, id selectRow) {
            [sender setTitle:[NSString stringWithFormat:@"+%@ ▼",selectValue] forState:UIControlStateNormal];
            self->selectCode = selectValue;
        }];
    } failure:^(NSURLSessionTask * _Nonnull operation, NSError * _Nonnull error) {
        
    }];
}

-(void)textChange:(QMUITextField *)field{
    DLog(@"wwww===%@",field.text);
    if (field.text.qmui_trimAllWhiteSpace.length < 1) {
        nextBtn.backgroundColor = MyColor(@"#D7E8FF");
//        nextBtn.userInteractionEnabled = YES;
    }else{
        nextBtn.backgroundColor = MYBlue;
//        nextBtn.userInteractionEnabled = NO;
    }
}

@end
